from rest_framework.permissions import IsAuthenticatedOrReadOnly
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status

from home_design.models import Style, StyleVoting


class StyleVotingView(APIView):
    permission_classes = [IsAuthenticatedOrReadOnly]

    def get_style_object(self, style_id):
        try:
            style = Style.objects.get(id=style_id)
        except Style.DoesNotExist:
            return Response({'message': '该单品不存在'}, status=status.HTTP_400_BAD_REQUEST)
        return style

    def post(self, request, style_id):
        """
        投票一个单品设计
        """
        user = request.user
        style = self.get_style_object(style_id)
        try:
            favorite = StyleVoting.objects.get(user=user, style=style)
        except StyleVoting.DoesNotExist:
            favorite = StyleVoting.objects.create(user=user, style=style)
            # favorite = StyleVoting(user=user, style=style)
        favorite.style_voting_status = 1
        favorite.save()

        return Response({'message': '投票成功'}, status=status.HTTP_200_OK)

    def delete(self, request, style_id):
        """
        取消收藏一个单品设计
        """
        user = request.user
        style = self.get_style_object(style_id)
        try:
            favorite = StyleVoting.objects.get(user=user, style=style)
        except StyleVoting.DoesNotExist:
            return Response({'message': '该用户未投票'}, status=status.HTTP_400_BAD_REQUEST)
        favorite.style_voting_status = 0
        favorite.save()
        return Response({'message': '取消投票成功'}, status=status.HTTP_200_OK)